/* eslint-disable */
import axios from 'axios';
// import {router} from '../router/index';
// import {Message, Loading} from 'element-ui';
import config from './config';
import User from '../session/User.js';
// import util from "../vuex/util";

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';

// console.log('====ENVIRONMENT=====', config.ENVIRONMENT);
// console.log('====api=====', config[config.ENVIRONMENT].api);

// axios.defaults.baseURL = config[config.ENVIRONMENT].api;
axios.defaults.baseURL = 'http://172.17.129.140:8888'
axios.defaults.withCredentials = true;

axios.interceptors.request.use(
  config => {
    let admin = User.getInfo();
    console.log('====admin=====', admin);
    // if (admin) {
      // if (admin.id) {
        // config.headers['auth-uid'] = admin.id;
		// config.headers['auth-uid'] = uni.getStorageSync('id');
		config.headers['auth-uid'] = uni.getStorageSync('idA');
		// config.headers['auth-uid'] = uni.getStorageSync('idB');
		// console.log(config.headers['auth-uid']);
      // }
      // if (admin.token) {
        // config.headers['auth-token'] = admin.token;
		// config.headers['auth-token'] = uni.getStorageSync('token');
		config.headers['auth-token'] = uni.getStorageSync('tokenA');
		// config.headers['auth-token'] = uni.getStorageSync('tokenB');
      // }
	  // console.log(config);
    // }
    return config;
  },
  err => {
    return Promise.reject(err);
  });

axios.interceptors.response.use(
  response => {
    console.log('=====response====', response);
    if (response.data !== null && (response.data.code === 'LOGIN_REQUIRED' || response.data.code === 'LOGIN_INVALID_TOKEN')) {
      User.logout();
      router.push({name: 'login'});
      return {};
    }
    else if (response.headers['content-type'] === 'application/octet-stream') {
      return response;
    }
    return response.data;
  },
  err => {
    console.log('====err=====', err);
    if (err && err.response) {

      if (err.response.data instanceof Blob) {

        return new Promise((resolve, reject) => {
          var reader = new FileReader();
          reader.readAsText(err.response.data, 'utf-8');
          reader.onload = function (e) {
            let result = reader.result;
            reject({response: {data: JSON.parse(result)}});
          };
        });
      }

      let message = err.response.data.msg;
      switch (err.response.status) {
        case 401:
          User.logout();
          router.push({name: 'login'});
          break;
        case 423:
          message = '资源已被使用，删除失败!';
          break;
      }
      Message.error(message || '服务器错误！');
    }
    if (!err || !err.response || !err.response.data || !err.response.data.msg
      || err.response.data.msg.length === 0) {
      err = {response: {data: {msg: '服务器错误！'}}};
    }
    return Promise.reject(err);
  }
);

export function formUrl(url, data) {
  if (!data) {
    return url;
  }

  let s = [];
  for (let k in data) {
    let v = data[k];

    // 2020-12-15 key
    if (!v) continue;

    if (v instanceof Array) {
      for (let vs in v) {
        s.push(k + '=' + v[vs]);
      }

    } else {
      s.push(k + '=' + data[k]);
    }
  }
  if (url.indexOf('?') !== -1) {
    return url + '&' + s.join('&');
  } else {
    return url + '?' + s.join('&');
  }
}

let Api = {};
Api.baseUrlAppending = function (url) {
  return config[config.ENVIRONMENT].api + url;
};
Api.httpGet = function (url, params) {
  return axios.get(formUrl(url, params));
};

Api.httpPost = function (url, params) {
  return axios.post(url, params);
};

Api.httpPut = function (url, params) {
  return axios.put(url, params);
};

Api.httpPatch = function (url, params) {
  return axios.patch(url, params);
};

Api.httpDelete = function (url, params) {
  return axios.delete(formUrl(url, params));
};

Api.httpGetOpenWindow = function (url) {
  window.open(Api.baseUrlAppending(url), '_blank');
}

Api.httpGetDownload = function (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(formUrl(url, params), {responseType: 'blob'}).then((res) => {
      openDownload(res);
      resolve();
    }).catch(err => {
      Message.error(err.response.data.msg);
    });
  });

  function openDownload(res) {
    const blob = new Blob([res.data], {type: 'application/octet-stream;charset=utf-8'});
    let regexFileName = /filename=\"(.*)\"/;
    let fileName = res.headers['content-disposition'].match(regexFileName)[1];
    fileName = decodeURIComponent(escape(fileName));
    if ('download' in document.createElement('a')) { // 非IE下载
      const elink = document.createElement('a');
      elink.download = fileName;
      elink.style.display = 'none';
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName);
    }
  }
};
export const LogApi = {
  save: params => {
    return httpPost(`/api/log`, params);
  }
};

export default Api;
